<template>
  <div class="course-edit-container">
    <!-- 返回箭头 -->
    <div class="header">
      <el-button 
        icon="arrow-left"
        @click="handleBack"
        class="back-button"
      ></el-button>
    </div>
    
    <!-- 表单区域 -->
    <el-form 
      :model="formData"
      ref="formRef"
      label-width="120px"
      class="course-form"
      :rules="rules"
    >
         
      <el-form-item label="学生姓名" prop="studentId">

        <el-select
              v-model="formData.studentId"
              filterable
              placeholder="请选择学生"
              style="width: 240px"
            >
              <el-option
                v-for="item in studentList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>

      </el-form-item>

      <el-form-item label="课程名称" prop="courseIds">
        
          <el-select
              v-model="formData.courseIds"
              filterable
              placeholder="请选择课程"
              style="width: 240px"
            >
              <el-option
                v-for="item in courseList"
                :key="item.id"
                :label="item.courseName"
                :value="item.id"
              />
            </el-select>



      </el-form-item>
      
      <!-- <el-form-item label="学生ID" prop="studentId">
        <el-input v-model="formData.studentId" placeholder="请输入学生ID" />
      </el-form-item> -->
      
      <!-- <el-form-item label="审核状态" prop="auditStatus">
        <el-radio-group v-model="formData.auditStatus">
          <el-radio :label="0">未审核</el-radio>
          <el-radio :label="1">已审核</el-radio>
        </el-radio-group>
      </el-form-item> -->
      
      <!-- <el-form-item v-if="formData.auditStatus === 1" label="审核原因" prop="auditReason">
        <el-input v-model="formData.auditReason" type="textarea" placeholder="请输入审核原因" />
      </el-form-item> -->
    </el-form>
    
    <!-- 底部按钮 -->
    <div class="button-group">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import * as courseApi from '@/api/studentCourseManage.js'
import * as studentApi from '@/api/studentManage.js'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const isEditMode = ref(false)
// 表单验证规则
const rules = {
  studentId: [{ required: true, message: '请输入学生ID', trigger: 'blur' }],
  // 验证非空，数组长度大于0
  courseIds: [{ required: true, message: '请选择课程', trigger: 'change' }, 
   {
      validator: (rule, value, callback) => {
        if (value && formData.courseIds.length == 0) {
          callback(new Error('请选择课程'))
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
}

// 表单数据
const formData = reactive({
  studentId: '',
  courseIds: []
})
// 学生列表
const studentList = ref([])
// 课程列表
const courseList = ref([])


// let studentOptions = computed(() => {
//   let filtered = studentList.filter(v => v.name.includes(formData.studentId))
//   return filtered.map(item => ({
//     label: item.name,
//     value: item.id
//   }))
// })
// let courseOptions = computed(() => {
//   let filtered = courseList.filter(v => v.name.includes(formData.courseIds))
//   return filtered.map(item => ({
//     label: item.name,
//     value: item.id
//   }))
// })

// 现获取学生列表
function getStudentList() {
  studentApi.studentList().then(res => {
    if (res.code === 200) {
      studentList.value = res.data.rows || [];
    }
  })
}

// 现获取课程列表
function getCourseList() {
  courseApi.courseList().then(res => {
    if (res.code === 200) {
      courseList.value = res.data.rows || [];
    }
  })
}


// 获取课程数据
const getCourseData = async () => {
  const rowId = route.params.id
  isEditMode.value = courseId !== 'new'

  if (isEditMode.value) {
    try {
      const res = await courseApi.getStudentCourseById(rowId)
      if (res.code === 200) {
        Object.assign(formData, res.data)
      }
    } catch (error) {
      ElMessage.error('选课失败')
    }
  } else {
    // 新增模式，重置表单
    Object.assign(formData, {
     studentId: '',
     courseIds: []
    })
  }
}

// 返回上一页
const handleBack = () => {
  router.go(-1)
}

// 取消按钮
const handleCancel = () => {
  router.go(-1)
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await courseApi.chooseCourses(formData)
        if (res.code === 200) {
          ElMessage.success(isEditMode.value ? '选课成功' : '选课成功')
          router.push('/studentCourseManage/index')
        }
      } catch (error) {
        ElMessage.error('选课失败')
      }
    }
  })
}

// 监听审核状态变化
// watch(
//   () => formData.auditStatus,
//   (newVal) => {
//     if (newVal === 0) {
//       formData.auditReason = ''
//     }
//   }
// )

// 页面加载时获取数据
onMounted(() => {
  getCourseData()
  getStudentList()
  getCourseList()

})
</script>

<style scoped>
.course-edit-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  margin-bottom: 30px;
}

.back-button {
  font-size: 18px;
}

.course-form {
  margin-bottom: 40px;
}

.button-group {
  display: flex;
  justify-content: center;
  gap: 20px;
}
</style>